import { defineStore } from 'pinia'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { post } from '@/utils/request'

export default defineStore('workstation-inspect-store', {
  state: () => {
    return {
      sideList: [],
      isLoading: false,
      isDisabled: true,
      recordCode: '', //样本号
      recordDate: dayjs().format('YYYY-MM-DD') || '', // 日期
      barCode: '', //条形码
      currentInstrument: {}, // 当前选择的仪器
      currentPatient: {}, // 当前选择患者
      // 当前数据集
      currentData: {
        lisApply: {},
        lisRecordItemList: [],
        lisRecord: {}
      },
      params: {}
    }
  },
  actions: {
    // 获取数据
    async getOrderData(status = 3) {
      if (this.currentPatient.lsh || this.barCode) {
        this.isLoading = true
        if (status === 3) {
          this.params = {
            lsh: this.currentPatient.lsh,
            barCode: this.barCode.trim(),
            recordCode: this.recordCode || null
          }
        } else {
          this.params = {
            lsh: this.currentPatient.lsh,
            barCode: status === 2 ? this.barCode.trim() : undefined,
            recordCode: status === 1 ? this.recordCode || null : undefined
          }
        }
        const { code, data, msg } = await post('/lis/LisRecord/getLisRecord', this.params)
        this.isLoading = false

        if (code !== 0) return message.error(msg || '请求失败')
        const { applResponse = {}, lisRecordItemList = {}, lisRecord = {}, lisApply = {} } = data
        this.currentData = { lisRecordItemList, lisRecord, applResponse, lisApply }
        this.currentPatient = applResponse
        lisRecord.samplingTime && (this.recordDate = lisRecord.samplingTime)
        this.isDisabled = !(applResponse.status !== '1' && applResponse.lsh)
        lisRecord.recordCode && (this.recordCode = lisRecord.recordCode) //赋值样本号
        lisRecord.barCode && (this.barCode = lisRecord.barCode) //赋值条形码
      }
    },
    //生成样本号
    async getSampleNumber() {
      const { code, data, msg } = await post('/lis/LisRecord/getSampleNumber', { lisInstrumentId: this.currentInstrument.id })
      if (code !== 0) return message.error(msg || '请求失败')
      this.recordCode = data
    },
    //重置
    reset(isGetSampleNumber = true) {
      this.recordCode = ''
      this.barCode = ''
      this.isDisabled = true
      this.currentPatient = {}
      this.currentData = {
        lisApply: {},
        lisRecordItemList: [],
        lisRecord: {}
      }
      isGetSampleNumber && this.getSampleNumber()
    }
  }
})
